﻿using Microsoft.Practices.Unity;
using Sasa.QualityTools.CodeAnalysis.Core.Models;
using Sasa.QualityTools.CodeAnalysis.Core.Views;
using Sasa.QualityTools.CodeAnalysis.Core.VisualStudio;
using Sasa.QualityTools.CodeAnalysis.FxCopIntegrator.Commands.Behaviors;
using Sasa.QualityTools.CodeAnalysis.FxCopIntegrator.ViewModels;
using System;
using System.IO;

namespace Sasa.QualityTools.CodeAnalysis.FxCopIntegrator.Commands
{
    [MenuCommand(Constants.Solution.Id, Constants.Solution.EditDictionary)]
    public class EditFxCopDictionaryCommand : CommandBase<CommandExecutionContext>, ICommandBehavior<CommandExecutionContext>
    {
        public EditFxCopDictionaryCommand(IUnityContainer container)
            : base(container)
        {
            Behaviors.Add(this);
        }


        public void Behave(CommandExecutionContext context)
        {
            var ide = Container.Resolve<IIde>();
            var solution = ide.Solution;
            var view = Container.Resolve<IFxCopDictionaryView>();
            var model = BuildupViewModel();

            model.Saving += delegate
            {
                ide.Checkout(solution.FxCopDictionaryPath);
            };
            model.Saved += delegate
            {
                solution.AddSolutionFolder(Core.Constants.CodeAnalysisConfigurationDirName).AddFromFile(solution.FxCopDictionaryPath);
            };
            model.CloseRequired += delegate
            {
                view.Close();
            };

            view.DataContext = model;
            view.ShowModal();
        }

        private FxCopDictionaryViewModel BuildupViewModel()
        {
            var solution = Container.Resolve<IIde>().Solution;
            var option = Container.Resolve<IFxCopIntegratorPackage>().GeneralOption;
            var buildinDictionaryPath = Path.Combine(Path.GetDirectoryName(option.FxCopCmdPath), "CustomDictionary.xml");

            var buildin = new FxCopDictionary(buildinDictionaryPath);
            var custom = new FxCopDictionary(solution.FxCopDictionaryPath);

            return new FxCopDictionaryViewModel(buildin, custom);
        }
    }
}
